import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.Flags.Flag;
import javax.mail.search.FlagTerm;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class Gmail implements Runnable
{

	public static int NumberOfEmails; 
	public static int NumberOfUnreadEmails = 0;
	public static String Username;
	public static String Password;
	public static int MailControlInterval=6; //seconds
	public static Folder Inbox;


	public Gmail(){

		Properties props = System.getProperties();
		props.setProperty("mail.store.protocol", "imaps");
		try
		{
			/*  Create the session and get the store for read the mail. */
			Session session = Session.getDefaultInstance(props, null);
			Store store = session.getStore("imaps");
			store.connect("imap.gmail.com",Username, Password);

			/*  Mention the folder name which you want to read. */
			Inbox = store.getFolder("Inbox");
		}
		catch (NoSuchProviderException e)
		{
			e.printStackTrace();
			System.exit(1);
		}
		catch (MessagingException e)
		{
			JOptionPane jop = new JOptionPane();
			JOptionPane.showMessageDialog(jop, "Can not login to server. Check your credentials!");
			System.exit(2);
		}

	}

	public static int CheckMail()
	{

		try {
			NumberOfEmails = Inbox.getUnreadMessageCount();
			NumberOfUnreadEmails = NumberOfEmails;
		} 
		
		catch (MessagingException e) {
			e.printStackTrace();
		}

		return NumberOfEmails;
	}

	public static boolean NewMailExists(){

		if(CheckMail() != NumberOfUnreadEmails)
			return true;
		else
			return false;

	}

	@Override
	public void run() {

		
		try {
			for(;;)
			{
			Thread.sleep(MailControlInterval*1000);
			if(NewMailExists())
				MailInfoWindow.Show();
				;
			
			}
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}


}
